﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using YlisChat.Models;
using System.IO;

namespace YlisChat.Controllers
{
    [Authorize]
    public class AttachmentController : BaseController
    {
        // GET: api/Attachment
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        /// <summary>
        /// Get the attachment metadata
        /// GET: api/Attachment/guid
        /// </summary>
        /// <param name="id">the attachment guid</param>
        /// <returns></returns>
        [ResponseType(typeof(Attachments))]
        public async Task<IHttpActionResult> Get(string id)
        {
            if (String.IsNullOrWhiteSpace(id))
                return this.StatusCode(HttpStatusCode.BadRequest);

            Attachments attachment = await (from att in db.Attachments
                                            where att.Id == id
                                            select att).FirstOrDefaultAsync();
            if (attachment == default(Attachments))
                return this.NotFound();

            attachment.InternalName = String.Format("{0}://{1}/api/Download/{2}", Request.RequestUri.Scheme, Request.RequestUri.Authority, attachment.Id);
            return this.Ok(attachment);
            //return this.Ok(String.Format("~/App_Data/Uploads/{0}", Path.GetFileName(attachment.InternalName)));
        }

        /// <summary>
        /// Posts a new attachment, requires a multipart/form-data post.
        /// </summary>
        /// <returns>a list of attachment GUIDs</returns>
        [ResponseType(typeof(List<String>))]
        public async Task<IHttpActionResult> Post()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                return this.StatusCode(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/App_Data/Uploads");
            MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root);

            try
            {
                List<String> guids = new List<string>();

                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    Guid fileId = Guid.NewGuid();
                    //Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    //Trace.WriteLine("Server file path: " + file.LocalFileName);
                    string fileName = file.Headers.ContentDisposition.FileName.Trim('\\', '"');
                    //IE Fix for paths (removes the C:\folder)
                    int slashIndex = fileName.LastIndexOf("\\");
                    if (slashIndex > -1)
                        fileName = fileName.Substring(slashIndex + 1);
                    AttachmentType type = GetByExtension(fileName);
                    if (type == AttachmentType.UNKNOWN)
                        continue;
                    Attachments attachment = new Attachments()
                    {
                        Id = fileId.ToString(),
                        Type = type,
                        OriginalName = fileName,
                        InternalName = file.LocalFileName
                    };

                    db.Attachments.Add(attachment);
                    await db.SaveChangesAsync();
                    guids.Add(fileId.ToString());
                }
                return this.Ok(guids);
            }
            catch (System.Exception e)
            {
                return this.StatusCode(HttpStatusCode.InternalServerError);
            }
        }

        private AttachmentType GetByExtension(string filename)
        {
            if (filename.EndsWith(".jpg") || filename.EndsWith(".png"))
                return AttachmentType.PICTURE;

            if (filename.EndsWith(".wav") || filename.EndsWith(".mp3"))
                return AttachmentType.VOICE;

            return AttachmentType.UNKNOWN;
        }
    }
}
